package com.dong.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dong.entity.UserEntity;
import com.dong.service.UserService;
import com.dong.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AjaxJsonServlet extends HttpServlet {
	static UserService goodsService = new UserServiceImpl();
	private static ObjectMapper mapper = new ObjectMapper();
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setCharacterEncoding("UTF-8");
		String method = arg0.getParameter("method");
		if ("save".equals(method)) {
			save(arg0, arg1);
		} else if ("delete".equals(method)) {
			delete(arg0, arg1);
		} else if ("edit".equals(method)) {
			edit(arg0, arg1);
		} else if ("query".equals(method)) {
			query(arg0, arg1);
		}
	}

	private void save(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		UserEntity userEntity = mapper.readValue(arg0.getParameter("data"), UserEntity.class);
		goodsService.addOrUpdate(userEntity);
		PrintWriter out = arg1.getWriter();
		out.print("添加成功");

	}

	private void edit(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
//		        Long id = Long.valueOf(arg0.getParameter("id"));
		        Long id = Long.valueOf(arg0.getParameter("id"));
	 			UserEntity user = goodsService.getById(id);
	 			PrintWriter out = arg1.getWriter();
	 			out.print(mapper.writeValueAsString(user));
	}

	private void delete(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
//		Long id = Long.parseLong(arg0.getParameter("id"));
		Long id = Long.valueOf(arg0.getParameter("id"));
		System.out.println(arg0.getParameter("id"));
		goodsService.delete(id);
		PrintWriter out = arg1.getWriter();
		out.print("success");

	}

	private void query(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
//		转换json对象

		PrintWriter out = arg1.getWriter();
		out.print(mapper.writeValueAsString(goodsService.listAll()));

	}

}
